<?php
namespace app\common\service\SystemConfigService\Transit;

use app\model\BbcModel\Area;
use app\Normal;
use app\model\BbcModel\TransitTemplate;
use app\model\BbcModel\TransitArea;
use app\model\BbcModel\TransitRule;
use app\model\BbcModel\Goods;
use think\Db;
use think\Exception;

/*
 * @author banban
 * @datetime 2022-8-9 14:52:12
 * @copyright 板板<249366615@qq.com>
 * @filename TransitTemplateService
 */
class TransitTemplateService
{
    /**
     * 获取运费模板列表(分页)
     * @param array $param
     * @return array
     */
    public function getListByPage(array $param):array {
        $page=(isset($param['page'])&&$param['page']>0)?$param['page']:1;
        $limit=(isset($param['limit'])&&$param['limit']>0)?$param['limit']:20;
        if (empty($param['cid'])) {
            return Normal::returnCode(Normal::FAIL, 'cid必传');
        }
        $where=['cid'=>$param['cid'],'df'=>0];
        $list= TransitTemplate::instance()->listPages($where, $limit, $page);
        $total= TransitTemplate::instance()->countNum($where);
        foreach ($list as $key => $value) {
            $y_area = TransitArea::instance()->join('area','area.id=transit_area.area_id')->where(['transit_area.template_id'=>$value['id']])->where(['type'=>1])->column('area.name');
            if($y_area){
                $list[$key]['y_area'] = implode(',',$y_area);
            }else{
                $list[$key]['y_area'] = '';
            }
            $n_area = TransitArea::instance()->join('area','area.id=transit_area.area_id')->where(['transit_area.template_id'=>$value['id']])->where(['type'=>2])->column('area.name');
            if($n_area){
                $list[$key]['n_area'] = implode(',',$n_area);
            }else{
                $list[$key]['n_area'] = '';
            }
        }
        return Normal::returnCode(Normal::SUC, '获取成功',['list'=>$list,'total'=>$total]);
    }
    
    /**
     * 获取运费模板列表(不分页)
     * @param array $param
     * @return array
     */
    public function getListNoPage(array $param):array {
        if (empty($param['cid'])) {
            return Normal::returnCode(Normal::FAIL, 'cid必传');
        }
        $where=['cid'=>$param['cid'],'df'=>0];
        $list= TransitTemplate::instance()->lists($where);
        foreach ($list as $key => $value) {
            $y_area = TransitArea::instance()->join('area','area.id=transit_area.area_id')->where(['transit_area.template_id'=>$value['id']])->where(['type'=>1])->column('area.name');
            if($y_area){
                $list[$key]['y_area'] = implode(',',$y_area);
            }else{
                $list[$key]['y_area'] = '';
            }
            $n_area = TransitArea::instance()->join('area','area.id=transit_area.area_id')->where(['transit_area.template_id'=>$value['id']])->where(['type'=>2])->column('area.name');
            if($n_area){
                $list[$key]['n_area'] = implode(',',$n_area);
            }else{
                $list[$key]['n_area'] = '';
            }
        }
        return Normal::returnCode(Normal::SUC, '获取成功',$list);
    }
    

    /**
     * 新增运费模板
     * @return void
     */
    public function addTemplate($param){
        if(!isset($param['cid']) || !$param['cid']){
            return Normal::returnCode(Normal::FAIL, 'cid必传');
        }
        if(!isset($param['name']) || !$param['name']){
            return Normal::returnCode(Normal::FAIL, '模板名称不能为空');
        }
        if(mb_strlen($param['name']) >= 20){
            return Normal::returnCode(Normal::FAIL, '模板名称20字以内');
        }
        $area = 0;
        if(isset($param['area'])){
            $area = $param['area'];
//            $area_str = implode(',',$area);
            /*if($param['no_appoint']){

                $area_str = $area_str.','.$param['no_appoint'];
            }*/
//            $area_arr = json_decode($area_str,true);
//            $area_arr = explode(',',$area_str);
        }
        $insert_template_data['name'] = $param['name'];
        $insert_template_data['cid'] = $param['cid'];
        $insert_template_data['cd'] = time();
        $insert_template_data['up'] = time();
        $insert_template_data['status'] = 0;
        TransitTemplate::instance()->startTrans();
        try{
            if(isset($param['id']) && !empty($param['id'])){ //编辑
                $info = TransitTemplate::instance()->info(['id'=>$param['id'],'cid'=>$param['cid']]);
                $insert_template_data['cd'] = $info['cd'];
                $insert_template_data['up'] = time();
                $insert_template_data['status'] = $info['status'];
                TransitRule::instance()->del(['template_id' => $param['id']]);
                TransitArea::instance()->del(['template_id' => $param['id']]);
                TransitTemplate::instance()->edit(['id'=>$param['id']],$insert_template_data);
                $template_id = $param['id'];
            }else{ //新增
                if(!TransitTemplate::instance()->info(['cid'=>$param['cid']])){
                    $insert_template_data['status'] = 1;
                }
                $template_id = TransitTemplate::instance()->add($insert_template_data);
            }
            if(count($area) != 0){
                foreach ($area as $key => $value) {
                    if(!isset($value['first_weight']) || !$value['first_weight']){
                        throw new \Exception('请填写首重');
                        return Normal::returnCode(Normal::FAIL,'请填写首重');
                    }
                    $first_weight = $value['first_weight']*1000;
                    if((floor($first_weight) - $first_weight) !=0){
                        throw new \Exception('首重最多三位小数');
                        return Normal::returnCode(Normal::FAIL,'首重最多三位小数');
                    }
                    if(!isset($value['unit_weight']) || !$value['unit_weight']){
                        throw new \Exception('请填写增加的重量');
                        return Normal::returnCode(Normal::FAIL,'请填写增加的重量');
                    }
                    $unit_weight = $value['unit_weight']*1000;
                    if((floor($unit_weight) - $unit_weight) !=0){
                        throw new \Exception('增加的重量最多三位小数');
                        return Normal::returnCode(Normal::FAIL,'增加的重量最多三位小数');
                    }
                    if($value['first_weight'] < 0){
                        throw new \Exception('首重不能小于0');
                        return Normal::returnCode(Normal::FAIL,'首重不能小于0');
                    }
                    if($value['first_price'] < 0){
                        throw new \Exception('首重运费不能小于0');
                        return Normal::returnCode(Normal::FAIL,'首重运费不能小于0');
                    }
                    if($value['unit_weight'] < 0){
                        throw new \Exception('增加重量不能小于0');
                        return Normal::returnCode(Normal::FAIL,'增加重量不能小于0');
                    }
                    if($value['unit_price'] < 0){
                        throw new \Exception('增加重量运费不能小于0');
                        return Normal::returnCode(Normal::FAIL,'增加重量运费不能小于0');
                    }
                    //foreach($value['list'] as $k=>$v){
                        $insert_rule_data['first_weight'] = $first_weight;
                        $insert_rule_data['first_price'] = $value['first_price'];
                        $insert_rule_data['unit_weight'] = $unit_weight;
                        $insert_rule_data['unit_price'] = $value['unit_price'];
                        $insert_rule_data['cid'] = $param['cid'];
                        $insert_rule_data['template_id'] = $template_id;
                        $insert_rule_data['cd'] = time();

                        $rule_id = TransitRule::instance()->add($insert_rule_data);
    //                    $area_arr = explode(',',$v);
                        //$area_arr = $v;
                        foreach($value['list'] as $val){
                            $insert_area_data[] = ['cid'=>$param['cid'],'area_id'=>$val,'rule_id'=>$rule_id,'cd'=>time(),'type'=>1,'template_id'=>$template_id];
                        }
                        TransitArea::instance()->insertAll($insert_area_data);
                        unset($insert_area_data);
                   // }
                }
            }
            if(isset($param['no_appoint']) && $param['no_appoint']){ //选择了不可下单地区
//                $no_appoint_area = explode(',',$param['no_appoint']);
                $no_appoint_area = $param['no_appoint'];
                if(count($no_appoint_area) > 0){
                    foreach($no_appoint_area as $val){
                        $insert_no_appoint_data[] = ['cid'=>$param['cid'],'area_id'=>$val,'cd'=>time(),'type'=>2,'template_id'=>$template_id,'rule_id'=>0];
                    }
                    TransitArea::instance()->insertAll($insert_no_appoint_data);
                }

            }
            TransitTemplate::instance()->commit();
        }catch (\Exception $e){
            TransitTemplate::instance()->rollback();
            return Normal::returnCode(Normal::FAIL,'新增失败,'.$e->getMessage());
        }
        return Normal::returnCode(Normal::SUC,'操作成功');
    }

    /**
     * 模板详情
     * @param $param
     * @return void
     */
    public function TemplateInfo($param){
        if(!isset($param['id']) || !$param['id']){
            return Normal::returnCode(Normal::FAIL,'缺少模板ID');
        }
        $info = TransitTemplate::instance()->info(['id'=>$param['id']]);
        if(!$info){
            return Normal::returnCode(Normal::FAIL,'模板不存在');
        }
        $rule = TransitRule::instance()->lists(['template_id' => $param['id'], '_fields_' =>'id,first_weight,first_price,unit_weight,unit_price']);
        foreach($rule as $k=>$v){
            $rule[$k]['unit_weight']=$v['unit_weight']/1000;
            $rule[$k]['first_weight']=$v['first_weight']/1000;
            $rule[$k]['list'] = TransitArea::instance()->alias('a')->join('area b','b.id=a.area_id')->where(['a.rule_id'=>$v['id']])->column('b.id');
        }
        $data['id'] = $param['id'];
        $data['name'] = $info['name'];
        $data['no_area'] =TransitArea::instance()->alias('a')->join('area b','b.id=a.area_id')->where(['a.type'=>2,'template_id'=>$param['id']])->column('b.id');
        $data['status'] = $info['status'];
        $data['rule'] = $rule;
        return Normal::returnCode(Normal::SUC,'请求成功',$data);
    }

    /**
     * 设默认运费模板
     * @param $param
     * @return void
     */
    public function changedefault($param){
        if(!$param['id']){
            return Normal::returnCode(Normal::FAIL,'缺少模板ID');
        }
        $info = TransitTemplate::instance()->info(['id' =>$param['id'], 'df' =>0]);
        if(!$info){
            return Normal::returnCode(Normal::FAIL,'模板不存在');
        }
        TransitTemplate::instance()->startTrans();
        try{
            TransitTemplate::instance()->where(['df'=>0,'cid'=>$info['cid']])->update(['status'=>0]);
            TransitTemplate::instance()->where(['df'=>0,'id'=>$param['id']])->update(['status'=>1]);
            TransitTemplate::instance()->commit();
        }catch(\Exception $e){
            TransitTemplate::instance()->rollback();
            return Normal::returnCode(Normal::FAIL,'设置失败');
        }
        return Normal::returnCode(Normal::SUC,'操作成功');
    }

    /**
     * 刪除运费模板
     * @param $param
     * @return void
     */
    public function deltemplate($param){
        if(!$param['id']){
            return Normal::returnCode(Normal::FAIL,'缺少模板ID');
        }
        $info = TransitTemplate::instance()->info(['id' =>$param['id']]);
        if(!$info){
            return Normal::returnCode(Normal::FAIL,'模板不存在');
        }
        if($info['status'] == 1){
            return Normal::returnCode(Normal::FAIL,'默认模板不能删除');
        }
        TransitTemplate::instance()->startTrans();
        try{
            TransitTemplate::instance()->edit(['id'=>$param['id']],['df'=>1]);
            $goods_ids = Goods::instance()->where(['cid'=>$info['cid'],'template_id'=>$param['id']])->column('id');
            $default_id = TransitTemplate::instance()->info(['status'=>1])['id'];
            Goods::instance()->where(['cid'=>$info['cid'],'df'=>0])->where('id','in',$goods_ids)->update(['template_id'=>$default_id]);
            TransitTemplate::instance()->commit();
        }catch(\Exception $e){
            TransitTemplate::instance()->rollback();
            return Normal::returnCode(Normal::FAIL,'删除失败'.$e->getMessage());
        }
        return Normal::returnCode(Normal::SUC,'删除成功');
    }
}